<script setup lang="ts">
import * as THREE from 'three'; // 导入threejs

import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { onMounted } from 'vue';

// 容器元素
let container: HTMLElement;

// 加载图片
const bg = new URL('../../assets/login/images/sky.png', import.meta.url).href;

let scene: THREE.Scene; // 场景

// 创新场景
const initScene = () => {
  scene = new THREE.Scene(); // 创建场景
  scene.fog = new THREE.Fog('#000000', 0, 10000); // 创建雾化效果
};

// 背景盒尺寸
const boxSize = {
  width: 0,
  height: 0,
  depth: 0
};

// 创建背景
const initBackground = () => {
  // 创建纹理
  const texture: THREE.Texture = new THREE.TextureLoader().load(bg, () => {
    // 创建立方体
    const geometry = new THREE.BoxGeometry(
      boxSize.width,
      boxSize.height,
      boxSize.depth
    );
    // 创建材质
    const material = new THREE.MeshBasicMaterial({
      map: texture, // 纹理
      side: THREE.BackSide // 材质显示在内层
    });

    // 创建网格
    const mesh = new THREE.Mesh(geometry, material);
    // 添加到场景
    scene.add(mesh);
  });
};

// 相机
let camera: THREE.Camera;
// 相机在z轴上的位置
let CameraZ = 0;

// 创建相机
const initCamera = () => {
  const fav = 15; // 视野夹角
  const distance = boxSize.width / 2 / Math.tan(Math.PI / 12);

  CameraZ = Math.floor(distance - 700);
  camera = new THREE.PerspectiveCamera(
    fav,
    boxSize.width / boxSize.height,
    1,
    30000
  );
  camera.position.set(0, 0, CameraZ);
  camera.lookAt(0, 0, 0);
};

// 渲染器
let renderer: THREE.WebGLRenderer;

// 创建渲染器
const initRender = () => {
  renderer = new THREE.WebGLRenderer();
  // 定义尺寸
  renderer.setSize(boxSize.width, boxSize.height);
  container.appendChild(renderer.domElement);
};

const initOrbitControls = () => {
  const control: OrbitControls = new OrbitControls(camera, renderer.domElement);
  control.enabled = true;
  control.update();
};

onMounted(() => {
  // 1.创建容器
  container = document.getElementById('login') as HTMLElement;
  // 2.创建场景
  initScene();
  // 3.创建背景盒
  boxSize.width = container?.clientWidth as number;
  boxSize.height = container?.clientHeight as number;
  boxSize.depth = 1400;
  initBackground();

  // 4.创建相机
  initCamera();

  // 5.创建渲染器
  initRender();

  // 6.添加轨道控制器
  initOrbitControls();

  // 7.添加动画
  const animate = () => {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
  };
  animate();
});
</script>
<template>
  <div id="login"></div>
</template>

<style scoped lang="scss">
#login {
  width: 100%;
  height: 100vh;
}
</style>
